package cn.practice.chat.security;

import cn.hutool.core.util.StrUtil;
import cn.practice.chat.feign.UserApiFeign;
import cn.practice.chat.lang.Result;
import cn.practice.chat.response.user.LoginUser;
import cn.practice.chat.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName token 验证处理器
 * @Description:
 * @Author A-TAO
 * @Date 2022/10/19
 * @Version V1.0
 **/
@Slf4j
public class TokenAuthenticationFilter extends BasicAuthenticationFilter {

    @Autowired
    private UserApiFeign userApiFeign;

    @Autowired
    private JwtUtils jwtUtils;

    public TokenAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String url = request.getRequestURI();
        // 不验证feign接口
        if(url.startsWith("/feign/")){
            chain.doFilter(request, response);
        } else {
            // 获取token
            String jwt = request.getHeader(jwtUtils.getHeader());
            log.info("JwtAuthenticationFilter开始token校验，获取到token={}", jwt);
            if(StrUtil.isBlankOrUndefined(jwt)){
                // 给其它的过滤器
                chain.doFilter(request, response);
                //jwtAccessDeniedHandler.handle(request, response , new AccessDeniedException("Unauthorized"));
                return;
            }
            Claims claims = jwtUtils.getClaimByToken(jwt);
            log.info("JwtAuthenticationFilter获取Claims，Claims={}", claims);
            if(ObjectUtils.isEmpty(claims)){
                throw new JwtException("token异常");
            }
            if(jwtUtils.isTokenExpired(claims)){
                throw new JwtException("token已经过期");
            }
            String username = claims.getSubject();

            Result<LoginUser> userResult = userApiFeign.getUser(username);
            log.info("调用user服务查询用户详情，userResult={}", userResult);
            LoginUser userResultData = userResult.getData();

            // 获取用户的权限信息
            UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(userResultData, null, null);
            SecurityContextHolder.getContext().setAuthentication(token);
            chain.doFilter(request, response);
        }

    }
}
